<template>
  <FormDialog :formOption="formOption" :form="form" :rule="rule" ref="dialogRef" :reload="reload"/>
</template>

<script setup lang="ts">
import FormDialog from "~/components/common/FormDialog.vue";
import {
  useApi
} from "~/composeables";
import {FormFieldType, FormOption} from "~/models/data/form";
import BookCategoryCache from "~/store/booksvr/bookCategoryCache";
import DepartmentCache from "~/store/system/departmentCache";
import BookStatusCache from "~/store/booksvr/bookStatusCache";

const props = defineProps<{
  reload: Function,
}>();

const api = useApi();

const dialogRef = ref<any>(null);

const submitFunc = (model : any)=>{
  api.bookBookApi.update(model)
      .then(res => {
        if (res.success) {
          ElMessage.success("提交数据成功！");
          if (props.reload) {
            props.reload();
          }
          close();
        } else {
          ElMessage.error("数据提交失败,请重新尝试！");
        }
      })
      .catch(err => {
        console.error(err);
        ElMessage.error("数据提交失败");
      })
}

const formOption : FormOption = {
  title : '修改图书信息',
  width : 480,
  labelWidth : 120,
  fieldList : [
    {
      fieldName: 'name',
      verboseName: '书籍名称',
      fieldType: FormFieldType.input,
    },
    {
      fieldName: 'identityKey',
      verboseName: '书籍标识',
      fieldType: FormFieldType.input,
    },
    {
      fieldName: 'authors',
      verboseName: '书籍作者',
      fieldType: FormFieldType.input,
    },
    {
      fieldName: 'publisher',
      verboseName: '出版社',
      fieldType: FormFieldType.input,
    },
    {
      fieldName: 'pubDate',
      verboseName: '发布时间',
      fieldType: FormFieldType.date,
    },
    {
      fieldName: 'categoryId',
      verboseName: '图书分类',
      fieldType: FormFieldType.cascader,
      selectSource: BookCategoryCache.bookCategoryTreeSelectSource,
      isMultiSelect: false,
    },
    {
      fieldName: 'departmentId',
      verboseName: '所属单位',
      fieldType: FormFieldType.cascader,
      selectSource: DepartmentCache.departmentTreeSelectSource,
      isMultiSelect: false
    },
    {
      fieldName: 'status',
      verboseName: '当前状态',
      fieldType: FormFieldType.select,
      selectSource: BookStatusCache.bookStatusSelectSource,
      isMultiSelect: false
    },
    {
      fieldName: 'description',
      verboseName: '书籍描述',
      fieldType: FormFieldType.textarea,
    },
    {
      fieldName: 'thumbnail',
      verboseName: '封面图',
      fieldType: FormFieldType.upload,
      uploadAction: 'upload',
      uploadFormats: ['jpg', 'jpeg', 'png', 'webp', 'gif']
    }
  ],
  submitFunc : submitFunc,
}

const form : any = ref({})

const rule = []

const open = (model: any)=>{
  dialogRef.value.open(JSON.parse(JSON.stringify(model)));
}

const close = ()=>{
  dialogRef.value.close();
}

defineExpose({open, close, dialogRef})

</script>